﻿using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;

using Sunyi.Project.WebPoint.Configuration;

namespace Sunyi.Project.WebPoint.Common
{
    public static class DbHelper
    {
        public static DataTable ExecuteCommand(string sqlCommand, Dictionary<string, object> parameters = null)
        {
            return ExecuteCommand(SystemConfiguration.DBConnectionString, sqlCommand, parameters);
        }

        public static DataTable ExecuteCommand(string dbConnectionString, string sqlCommand, Dictionary<string, object> parameters = null)
        {
            DataTable dt = new DataTable();

            var adapter = new SqlDataAdapter(sqlCommand, dbConnectionString);

            if (parameters != null)
            {
                foreach (string key in parameters.Keys) adapter.SelectCommand.Parameters.Add(new SqlParameter(key, parameters[key]));
            }

            adapter.Fill(dt);

            return dt;
        }

        public static void ExecuteNonQuery(SqlConnection connection, string sqlCommand, Dictionary<string, object> parameters = null)
        {
            var command = connection.CreateCommand();
            command.CommandText = sqlCommand;

            if (parameters != null)
            {
                foreach (string key in parameters.Keys)
                {
                    string parameterKey = key.StartsWith(WebPointGlobalConstant.At) ? key : WebPointGlobalConstant.At + key;
                    command.Parameters.Add(new SqlParameter(parameterKey, parameters[key]));
                }
            }

            command.ExecuteNonQuery();
        }
    }
}
